package cn.frank.framework.king.conf.init.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;

import java.util.Arrays;

/**
 * @description: TODO
 * @author: renjiangyang
 * @date 2025/7/31 11:24:29
 * @since 1.8
 */
// ✅ 环境已准备：配置文件加载完成，但 Bean 还没创建
@Slf4j
public class EnvironmentPreparedListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    /**
     * 1. ApplicationStartingEvent
     * 2. ✅ ApplicationEnvironmentPreparedEvent   <-- 你监听的就是这个
     * 3. ApplicationContextInitializedEvent
     * 4. ApplicationPreparedEvent
     * 5. ContextRefreshedEvent
     * 6. ApplicationStartedEvent
     * 7. ApplicationReadyEvent
     * @param event
     */
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment env = event.getEnvironment();

        log.info(">>> 激活的 profiles: {}", Arrays.toString(env.getActiveProfiles()));

        log.info(">>> 加载的配置源（PropertySources）如下：");


        /**
         * configurationProperties      ConfigurationPropertySourcesPropertySource  Spring Boot 自动装配绑定的配置
         * servletConfigInitParams      StubPropertySource                          容器中配置的 <init-param> 参数
         * servletContextInitParams     StubPropertySource                          Servlet Context 中的 init 参数
         * systemProperties             PropertiesPropertySource                    JVM 启动参数，如 -Dserver.port=8080
         * systemEnvironment            SystemEnvironmentPropertySource             环境变量，例如 SERVER_PORT=8080
         * random                       RandomValuePropertySource                   支持 random.* 占位符（如 random.uuid）的内部配置
         * applicationConfig            OriginTrackedMapPropertySource              这通常是 .properties 或 .yml 文件加载进来的内容
         * defaultProperties            DefaultPropertiesPropertySource             设置的默认值
         */


        for (PropertySource<?> propertySource : env.getPropertySources()) {

            // 常见的 propertySource 有 applicationConfig: [file:./resources/application.properties]
            if (propertySource instanceof EnumerablePropertySource) {
                EnumerablePropertySource<?> eps = (EnumerablePropertySource<?>) propertySource;
                if (eps.getPropertyNames().length > 0) {
                    System.out.println("配置(" + propertySource.getName() + ")");
                    for (String propertyName : eps.getPropertyNames()) {
                        // 只输出关键属性（可自定义过滤），避免过长
                        // if (propertyName.startsWith("spring.") || propertyName.startsWith("server.") || propertyName.startsWith("logging.")) {
                        Object value = eps.getProperty(propertyName);
                        System.out.println("    |-- " + propertyName + " = " + value);
                        // }
                    }
                }
            }
        }
    }
}
